package edu.sandau.b23015110.controller;

import edu.sandau.b23015110.model.Customer;
import edu.sandau.b23015110.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;


@Controller
@RequestMapping("customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;
    @RequestMapping("list" )
    public String list(ModelMap map, Customer customer){
        if("".equals(customer.getName())){
            customer.setName(null);
        }
        if("".equalsIgnoreCase(customer.getMajor())){
            customer.setMajor(null);
        }
        map.put("customerList",customerService.findAll(customer));
        return "customer/list";
    }


    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
        customerService.deleteById(id);
        return "redirect:/customer/list";
    }


    @RequestMapping("create")
    public String create(){
        return "customer/create";
    }


    @RequestMapping("save")
    public String save(Customer s){
        if(s.getId()==null){
            s.setId(UUID.randomUUID().toString());
            customerService.save(s);
        }
        else{
            customerService.update(s);
        }
        return "redirect:/customer/list";
    }


    @RequestMapping("update/{id}")
    public String update(@PathVariable String id, ModelMap map){
        Customer s = customerService.getReferenceById(id);
        map.put("customer", s);
        return "customer/update";
    }

}
